'''
Created on Nov 29, 2010

@author: dexen
'''
import random
from dexen import BaseIndividual
from settings import GEN_SIZE, MUTATION_PROB

ALIVE = "Alive"
DEAD = "Dead"

class Individual(BaseIndividual):
    #constructor
    def __init__(self):
        BaseIndividual.__init__(self)
        self.state = ALIVE
        self.genotype = []
        for _ in range(GEN_SIZE):
            self.genotype.append(round(random.random(), 4))
        self.phenotype = None
        self.score_area = None
        self.score_vol = None

    #reproduction method for creating children
    def reproduce(self, ind):
        child1 = Individual()
        child2 = Individual()
        child1.genotype = []
        child2.genotype = []
        
        #crossover
        z = random.randint(1, GEN_SIZE-2)
        
        for i in range(z):
            child1.genotype.append(self.genotype[i])
            child2.genotype.append(ind.genotype[i])
            
        for i in range(z, GEN_SIZE):
            child1.genotype.append(ind.genotype[i])
            child2.genotype.append(self.genotype[i])
            
        #mutation
        for i in range(GEN_SIZE):
            if random.random() < MUTATION_PROB:
                child1.genotype[i] = random.random()
            if random.random() < MUTATION_PROB:
                child2.genotype[i] = random.random()
        
        #two new children
        return child1, child2
    
    #kill method for killing an individual
    def kill(self):
        self.state = DEAD
    
    #alive method
    def is_alive(self):
        return self.state == ALIVE 
    
    #printing method
    def __repr__(self):
        out = "---------- Individual ----------\n"
        out += "Id: %s\n"%(self._get_id()) 
        if self.genotype:
            out += "Genotype: Exists\n"
        else:
            out += "Genotype: None\n"
        if self.phenotype:
            out += "Phenotype: Exists\n"
        else:
            out += "Phenotype: None\n"        
        out += "Score Area: %s\n"%(self.score_area)
        out += "Score Volume: %s\n"%(self.score_vol)
        out += "-------------------------------\n"
        return out
    